package com.dajie.pt.controller.invitation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dajie.common.DictionaryServicesContext;
import com.dajie.common.dictionary.DictEnum;
import com.dajie.common.dictionary.model.Dict;
import com.dajie.common.dictionary.model.DictItem;
import com.dajie.common.dictionary.service.DictService;
import com.dajie.common.util.StringUtil;
import com.dajie.core.cv.service.ResumeService;
import com.dajie.core.invitation.service.InvitationService;
import com.dajie.core.job.service.JobServiceWrapper;
import com.dajie.core.profile.ProfileServicesContext;
import com.dajie.core.profile.service.CardInfoService;
import com.dajie.infra.user.model.UserBase;
import com.dajie.job.api.JobServicesContext;
import com.dajie.pt.controller.InvitationBaseController;
import com.dajie.pt.model.AuditBlacklist;
import com.dajie.pt.model.InvitationApply;
import com.dajie.pt.service.BlacklistService;
import com.dajie.pt.service.InvitationApplyService;
import com.dajie.pt.utils.DateTimeUtils;
import com.dajie.sms.SmsServicesContext;
import com.dajie.sms.model.DefaultTplKey;
import com.dajie.sms.model.SmsResponse;
import com.dajie.sms.service.SmsService;

@Controller
@RequestMapping("/ajax")
public class AjaxController extends InvitationBaseController
{
	private final String BlackCode = "dj-pt*";
	
	JobServiceWrapper jobService = JobServicesContext.getInstance().getJobService();


	CardInfoService cardInfoService = ProfileServicesContext.getInstance().getCardService();

	ResumeService resumeService = JobServicesContext.getInstance().getResumeService();

	static DictService dictService = DictionaryServicesContext.getInstance().getDictService();

	static Dict dictCity = dictService.getDict(DictEnum.DICT_CITY);

	static Dict dictMajor = dictService.getDict(DictEnum.DICT_MAJOR);

	static Dict dictLang = dictService.getDict(DictEnum.DICT_LANG);

	static Dict dictIndustry = dictService.getDict(DictEnum.DICT_POSITION_INDUSTRY);

	static Dict dictItskill = dictService.getDict(DictEnum.DICT_ITSKILL);

	private static final SmsService smsService = SmsServicesContext.getInstance().getSmsService();

	@Autowired
	BlacklistService<AuditBlacklist, Integer> blacklistService;

	@Autowired
	InvitationApplyService<InvitationApply, Integer> invitationApplyService;

	@RequestMapping("dict")
	@ResponseBody
	public String index(@RequestParam(value = "ajax", required = false) Integer ajax,
			@RequestParam(value = "type", required = true) String type,
			@RequestParam(value = "id", required = true) Integer id)
	{
		LOGGER.info("ajax/dict");
		List<DictItem> items = null;
		if ("city".equals(type))
		{
			items = getDictItems(id, dictCity);
		} else if ("major".equals(type))
		{
			items = getDictItems(id, dictMajor);
		} else if ("lang".equals(type))
		{
			items = getDictItems(id, dictLang);
		} else if ("position_industry".equals(type))
		{
			items = getDictItems(id, dictIndustry);
		}

		// [{id:110000, text: '北京'}]
		StringBuffer dictJson = new StringBuffer("[");
		for (DictItem item : items)
		{
			dictJson.append("{id:");
			dictJson.append(item.getId());
			dictJson.append(", text:'");
			dictJson.append(item.getName());
			dictJson.append("'},");
		}
		if (dictJson.indexOf(",") > 0)
		{
			dictJson = dictJson.replace(dictJson.lastIndexOf(","), dictJson.lastIndexOf(",") + 1, "");
		}
		dictJson.append("]");
		return dictJson.toString();
	}

	private List<DictItem> getDictItems(Integer id, Dict dict)
	{
		DictItem curItem = dict.getMap().get(id);
		List<DictItem> items = curItem.getChildren();
		if (items == null || items.size() == 0)
		{
			items = new ArrayList<DictItem>();
			items.add(curItem);
		}
		return items;
	}

	@RequestMapping("uploadcrossdomain")
	public void uploadCallback(HttpServletRequest request, HttpServletResponse response)
	{
		String fileName = request.getParameter("uploadinfo");
		String callback = request.getParameter("callback");
		if (StringUtils.isBlank(callback))
		{
			callback = "UPLOAD_CALLBACK";
		}

		// InvitationApply invitationApply =
		// this.getInvitationApplyByUid(request, getLoginUser().getUid());
		// invitationApply.setResumeFile(fileName);

		String directText = "<script type=\"text/javascript\">parent." + callback + "('" + fileName + "')</script>";
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		try
		{
			response.getWriter().println(directText);
		} catch (IOException e)
		{
			LOGGER.error("upload error:", e);
		}

	}

	@RequestMapping("saveMobile")
	@ResponseBody
	public String saveMobile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "mobile", required = true) String mobile,
			@RequestParam(value = "uid", required = true) Integer uid)
	{
		// List<AuditBlacklist> blacklist = blacklistService.findAll();
		// LOGGER.info("list.size:{}",blacklist.size());
		LOGGER.info("mobile:{},uid:{}", mobile, uid);
		if (StringUtils.isNotEmpty(mobile))
		{
			this.getInvitationApplyByUid(request, uid).setMobile(mobile);
		}

		return "OK";
	}

	@RequestMapping("savelivecity")
	@ResponseBody
	public String saveLivecity(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "livecity", required = true) Integer livecity,
			@RequestParam(value = "mobile", required = true) String mobile)
	{
		// List<AuditBlacklist> blacklist = blacklistService.findAll();
		// LOGGER.info("list.size:{}",blacklist.size());
		LOGGER.info("mobile:{},uid:{}", livecity, mobile);
		if (livecity != null && livecity > 0)
		{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile", mobile);
			ia.getBasicInfo().setLivecity(livecity);
			this.invitationApplyService.saveOrUpdate(ia);
		}

		return "OK";
	}

	@RequestMapping("checkresume")
	@ResponseBody
	public String checkResume(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "mobile", required = true) String mobile)
	{
		InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile", mobile);

		if (StringUtils.isEmpty(ia.getBasicInfo().getName()) || ia.getBasicInfo().getGender() == null
				|| ia.getBasicInfo().getGender() == 0 || ia.getBasicInfo().getBirthday() == null
				|| ia.getBasicInfo().getDomicile() == null || ia.getBasicInfo().getDomicile() == 0
				|| ia.getIntentionInfo().getStatus() == null || ia.getIntentionInfo().getStatus() == 0
				|| ia.getIntentionInfo().getIndustry() == null || ia.getIntentionInfo().getIndustry() == 0)
		{
			return "0";
		} else
		{
			return "1";
		}
	}

	@RequestMapping("validatemobile")
	@ResponseBody
	public String validateMobile(HttpServletRequest request,
			@RequestParam(value = "mobile", required = true) String mobile,
			@RequestParam(value = "email", required = false) String email)
	{
		if (!StringUtil.isMobileNO(mobile))
		{
			return "({result:-1,tips:'请填写正确的手机号，以便HR及时与你联系！'})";
		}

		InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile", mobile);
		if (ia == null)
		{
			this.getSecurityCode(request, mobile);
			return "({result:0,mail:2})";
		} else
		{
			if (email != null && email.equals(ia.getEmail()))
			{
				return getCheckPassDate(ia);

			} else
			{
				return "({result:2,mail:1})";
			}
		}
	}

	private String getCheckPassDate(InvitationApply ia)
	{
		UserBase userBase = this.getUserBase();
		Integer isLogin = 0;
		String name = StringUtil.isNotEmpty(ia.getBasicInfo().getName())?ia.getBasicInfo().getName():null;
		Integer livecity = ia.getBasicInfo().getLivecity()==null?null:ia.getBasicInfo().getLivecity();
		Integer livecityParent = ia.getBasicInfo().getLivecity()==null?null:dictCity.getMap().get(ia.getBasicInfo().getLivecity()).getParentId();
		if(userBase != null)
		{
			isLogin = 1;
			name = name == null?userBase.getName():name;
		}
		return  "({result:1,is_login:"+isLogin+",name:'" + (name != null?name:"") + "',livecity:'" + (livecity!=null?livecity:"")
				+ "',livecity_parent:'"+(livecityParent!=null?livecityParent:"")+"'})"; 
	}

	private String getSecurityCode(HttpServletRequest request, String mobile)
	{
//		Object oldCode = request.getSession().getAttribute("securitycode_" + mobile);
		String oldCode = this.invitationApplyService.getCode(mobile);
		//request.getSession().setAttribute("securitycode_checked", 0);
		if (oldCode != null)
		{
			LOGGER.info("securityCode {} fro {}", (String) oldCode, mobile);
			return (String) oldCode;
		}
		String code = genSecurityCode(request,mobile);
		LOGGER.info("securityCode {} fro {}", code, mobile);
		return code;
	}

	@RequestMapping("getsecuritycode")
	@ResponseBody
	public String genSecurityCode(HttpServletRequest request,String mobile)
	{
		Map<String, String> data = new HashMap<String, String>();
		data.put(DefaultTplKey.MOBILE.getKey(), mobile); // 目标手机号
		String code = ("" + (Math.random())).substring(2, 8);
		LOGGER.info("securitycode is {} for {}", code, mobile);
		data.put("securitycode", code); // 验证码
		try
		{
			SmsResponse res = smsService.sendSMS(1001, 104, data);
		 	//1001是业务类型号，104是短信模板号
		 	LOGGER.info("the res of sending sms:{}" ,res.getResult());
//			LOGGER.info("the res of sending sms:{}", "sms send jump");
		} catch (Exception e)
		{
			LOGGER.error("sms send error:", e);
		}
//		request.getSession().setAttribute("securitycode_" + mobile, code);
		this.invitationApplyService.saveCode(mobile, code);
		return code;
	}
	
	@RequestMapping("checksecuritycode")
	@ResponseBody
	public String checkSecurityCode(HttpServletRequest request, String mobile, String code, String email, String checked)
	{
		UserBase userBase = this.getUserBase();
//		Object securitycode = request.getSession().getAttribute("securitycode_" + mobile);
		String securitycode = this.invitationApplyService.getCode(mobile);
		if (BlackCode.equals(code) || (securitycode != null && StringUtil.isNotEmpty((String) securitycode) && securitycode.equals(code)))
		{
			// request.getSession().removeAttribute("securitycode_" + mobile);
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile", mobile);
			if (ia == null && userBase != null)
			{
				ia = this.invitationApplyService.findUniqueBy("uid",userBase.getUid());
			}
			if(ia == null)
			{
				ia = new InvitationApply();
			}
			ia.setMobile(mobile);
			ia.setEmail(email);
			ia.setStatus(0);
			if (userBase != null)
			{
				ia.setUid(userBase.getUid());
			}
			this.invitationApplyService.saveOrUpdate(ia);
			return getCheckPassDate(ia);

		} else
		{
			return "({result:0})";
		}
	}

	@RequestMapping("validatemobileandemail")
	@ResponseBody
	public String validateMobileAndEmail(HttpServletRequest request,
			@RequestParam(value = "mobile", required = true) String mobile,
			@RequestParam(value = "email", required = true) String email)
	{
		if (!StringUtil.isEmail(email))
		{
			return "请填写正确的邮箱地址，以便HR及时与你联系！";
		}

		InvitationApply invitationApply = this.invitationApplyService.findUniqueBy("mobile", mobile, "email", email);
		LOGGER.info(invitationApply.getEmail());
		return "";
	}

	@RequestMapping("checkemail")
	@ResponseBody
	public String checkEmail(HttpServletRequest request, @RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "mobile", required = false) String mobile,
			@RequestParam(value = "checked", required = false) Integer checked)
	{
		String res = "({result:2})";
		if (!StringUtil.isEmail(email))
		{
			return "({'result':'-1','tips':'请填写正确的邮箱地址，以便HR及时与你联系！'})";
		}
		if (StringUtil.isNotEmpty(mobile) && StringUtil.isMobileNO(mobile))
		{
			InvitationApply ia = invitationApplyService.findUniqueBy("mobile", mobile);
			if (email.equals(ia.getEmail()))
			{
				res = getCheckPassDate(ia);
				invitationApplyService.saveOrUpdate(ia);
			} else
			{
				this.getSecurityCode(request, mobile);
				res = "({result:0})";
			}
		} else if (checked == 1)
		{
			InvitationApply ia = invitationApplyService.findUniqueBy("mobile", mobile);
			ia.setEmail(email);
			invitationApplyService.saveOrUpdate(ia);
		}
		return res;
	}
	
	
	@RequestMapping("savegender")
	@ResponseBody
	public String saveGender(HttpServletRequest request,
			@RequestParam(value="mobile") String mobile,
			@RequestParam(value="gender") Integer gender)
	{
		try
		{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile",mobile);
			ia.getBasicInfo().setGender(gender);
			this.invitationApplyService.saveOrUpdate(ia);
		} catch (Exception e)
		{
			LOGGER.error("saveGender error:{}",e);
			return "error";
		}
		return "ok";
	}

	@RequestMapping("savebirthday")
	@ResponseBody
	public String saveBirthday(HttpServletRequest request,
			@RequestParam(value="mobile")String mobile,
			@RequestParam(value="birthday") String birthday)
	{
		try
		{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile",mobile);
			if(StringUtil.isNotEmpty(birthday))
			{
				ia.getBasicInfo().setBirthday(DateTimeUtils.convertStringToDate(birthday));
				this.invitationApplyService.saveOrUpdate(ia);
				
			}
		}catch(Exception e)
		{
			LOGGER.error("saveBirthday error:{}",e);
			return "error";
		}
		return "ok";
	}
	
	
	@RequestMapping("savedomicile")
	@ResponseBody
	public String saveDomicile(HttpServletRequest request,
			@RequestParam(value="mobile")String mobile,
			@RequestParam(value="domicile") Integer domicile)
	{
		try
		{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile",mobile);
			ia.getBasicInfo().setDomicile(domicile);
			this.invitationApplyService.saveOrUpdate(ia);
		}catch(Exception e)
		{
			LOGGER.error("saveDomicile error:{}",e);
			return "error";
		}
		return "ok";
	}
	
	
	@RequestMapping("saveworkyears")
	@ResponseBody
	public String saveWorkyears(HttpServletRequest request,
			@RequestParam(value="mobile") String mobile,
			@RequestParam(value="workyears") Integer workYears)
	{
		try{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile",mobile);
			ia.getBasicInfo().setWorkYears(workYears);
			this.invitationApplyService.saveOrUpdate(ia);
		}catch(Exception e)
		{
			LOGGER.error("saveWorkyears:{}",e);
			return "error";
		}
		return "ok";
	}
	
	
	@RequestMapping("saveqq")
	@ResponseBody
	public String saveQq(HttpServletRequest request,
			@RequestParam(value="mobile")String mobile,
			@RequestParam(value="qq")String qq)
	{
		try{
			InvitationApply ia = this.invitationApplyService.findUniqueBy("mobile",mobile);
			ia.getBasicInfo().setQq(qq);
			this.invitationApplyService.saveOrUpdate(ia);
		}catch(Exception e)
		{
			LOGGER.error("saveQa:{}",e);
			return "error";
		}
		return "ok";
	}
	
}